package com.itheima.reggie.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.domain.Setmeal;
import com.itheima.reggie.domain.SetmealDish;
import com.itheima.reggie.dto.PageDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import com.itheima.reggie.vo.CustomException;
import com.itheima.reggie.vo.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 新增套餐
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public R addSetmeal(SetmealDto dto) {
        //1参数校验
        if (dto == null) {
            return R.error("参数异常");
        }
        //判断套餐是否存在
        Setmeal one = this.getOne(Wrappers.lambdaQuery(Setmeal.class).eq(Setmeal::getName, dto.getName()));
        if (ObjectUtil.isNotNull(one)) return R.error("套餐已存在");

        //2保存套餐数据
        setmealMapper.insert(dto);

        //3包含套餐的菜品信息
        List<SetmealDish> setmealDishes = dto.getSetmealDishes();

        //4补全套餐菜品信息
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(dto.getId());
        }

        //5保存套餐菜品信息(plus的批量添加)
        setmealDishService.saveBatch(setmealDishes);
        return R.success("保存成功");
    }

    /**
     * 分页查询
     *
     * @return
     */
    @Override
    public R findPage(PageDto dto) {
        //1.参数校验
        if (dto == null) {
            return R.error("参数有误");
        }
        //2.分页查询
        Page<Setmeal> page = new Page<>(dto.getPage(), dto.getPageSize());
        //3.条件参数
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(dto.getName())) {
            wrapper.like(Setmeal::getName, dto.getName());
        }
        Page<Setmeal> pageInfo = setmealMapper.selectPage(page, wrapper);

        //todo 1把老setmeal page转换为new setmealDto的page
        Page newPage = new Page();
        //todo 2.把老page的数据放入新page
        //todo 使用copy
        BeanUtils.copyProperties(pageInfo, newPage);
        //todo 3.查询每个套餐的分类然后进行封装
        List<Setmeal> setmeals = newPage.getRecords();
        //todo 4.List<Setmeal>转换List<SetmealDto>
        String s = JSON.toJSONString(setmeals);
        List<SetmealDto> setmealDtos = JSON.parseArray(s, SetmealDto.class);

        setmealDtos.stream().map(c -> {
            //根据分类id查询出分类名称
            String categoryName = categoryMapper.selectById(c.getCategoryId()).getName();
            c.setCategoryName(categoryName);
            return c;
        }).collect(Collectors.toList());

        newPage.setRecords(setmealDtos);
        return R.success(newPage);
    }

    /**
     * 删除套餐
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public void deleteById(List<Long> ids) {
        //查询套餐状态，判断是否可删除
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Setmeal::getStatus, 1);
        wrapper.in(Setmeal::getId, ids);

        int count = this.count(wrapper);
        if (count > 0) {
            //如果不能删除，抛出一个业务异常
            throw new CustomException("套餐正在售卖中，不能删除");
        }

        //可以删除，先删除套餐中的数据Seteal
        this.removeByIds(ids);

        LambdaQueryWrapper<SetmealDish> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.in(SetmealDish::getSetmealId, ids);
        //删除关系表中的数据SetmealDish
        setmealDishService.remove(deleteWrapper);
    }

    /**
     * 批量和单独修改菜品状态
     *
     * @param status
     * @param ids
     * @return
     */
    @Override
    public void status(Integer status, List<Long> ids) {
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ids != null, Setmeal::getId, ids);
        List<Setmeal> list = this.list(wrapper);
        for (Setmeal setmeal : list) {
            if (setmeal != null) {
                setmeal.setStatus(status);
                this.updateById(setmeal);
            }
        }
    }

    @Override
    public SetmealDto get(Long id) {
        //查询套餐基本信息，从stemeal表查询
        Setmeal setmeal = super.getById(id);

        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);

        //查询当前套餐对应的菜品信息，从stemeal_dish表查询
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishes = setmealDishService.list(wrapper);

        setmealDto.setSetmealDishes(setmealDishes);
        return setmealDto;
    }

    /**
     * 更新套餐信息，同时更新对应的菜品信息
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public void updateByIds(SetmealDto dto) {
        //更新setmeal表的基本信息
        super.updateById(dto);
        //清理当前套餐对应的菜品数据
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId, dto.getId());

        setmealDishService.remove(wrapper);

        //添加当前提交过来的菜品信息
        List<SetmealDish> setmealDishes = dto.getSetmealDishes();

        setmealDishes.stream().map((item) -> {
            item.setSetmealId(dto.getId());
            return item;
        }).collect(Collectors.toList());
         setmealDishService.saveBatch(setmealDishes);
    }

}
